#region Using

using System;
using System.Text;
using System.Text.RegularExpressions;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;

#endregion

[Extension("Embeds Youtube videos into posts and pages", "1.0", "Mads Kristensen")]
public class YouTube
{
	public YouTube()
	{
		Post.Serving += new EventHandler<ServingEventArgs>(Serving);
		Page.Serving += new EventHandler<ServingEventArgs>(Serving);
	}

	/// <summary>
	/// The regular expression used to find the Youtube video ID.
	/// </summary>
	private static readonly Regex REGEX = new Regex(@"\[youtube:(.*?)\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);

	/// <summary>
	/// Used in feeds where we cannot embed flash.
	/// </summary>
	private const string FEED_LINK = "<a href=\"http://youtube.com/watch?v={0}\" title=\"Youtube video\">Watch video</a>";

	/// <summary>
	/// Finds all matches in the content body and replaces it with an embedded flash player.
	/// </summary>
	private static void Serving(object sender, ServingEventArgs e)
	{
		if (!e.Body.Contains("[youtube:"))
			return;

		foreach (Match match in REGEX.Matches(e.Body))
		{
			string videoId = match.Groups[1].Value.Trim();

			if (e.Location != ServingLocation.Feed)
			{				
				string embed = string.Format(Html, videoId);
				e.Body = e.Body.Replace(match.Groups[0].Value, embed);
			}
			else
			{
				string link = string.Format(FEED_LINK, videoId);
				e.Body = e.Body.Replace(match.Groups[0].Value, link);
			}
		}
	}

	private static string _Html;
	/// <summary>
	/// Gets the HTML used for embedding the Youtube flash videos.
	/// </summary>
	public static string Html
	{
		get
		{
			if (_Html == null)
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("<object width=\"425\" height=\"350\">");
				sb.Append("<param name=\"movie\" value=\"http://www.youtube.com/v/{0}\"></param>");
				sb.Append("<param name=\"wmode\" value=\"transparent\"></param>");
				sb.Append("<embed src=\"http://www.youtube.com/v/{0}\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"425\" height=\"350\"></embed>");
				sb.Append("</object>");
				_Html = sb.ToString();
			}

			return _Html;
		}
	}

}
